<?php
App::uses('AppModel', 'Model');
App::uses('AuthComponent', 'Controller/Component');

class User extends AppModel {
	public $avatarUploadDir = 'img/avatars';
	var $actsAs = array('Acl' => array('type' => 'requester'));
	public $belongsTo = array('Group' => array(
            'className' => 'Group',
            'foreignKey' => 'group_id'
        ));
	
	/*public $validate = array(
	'username' => array
		('nonEmpty' => array('rule' => array('notEmpty'), 'message' => 'A username is required', 'allowEmpty' => false), 
			'between' => array('rule' => array('between', 5, 15), 
			'required' => true, 'message' => 'Usernames must be between 5 to 15 characters'), 
			'unique' => array('on' => 'create','rule' => array('isUniqueUsername'), 'message' => 'This username is already in use'), 
			'alphaNumericDashUnderscore' => array('rule' => array('alphaNumericDashUnderscore'), 'message' => 'Username can only be letters, numbers and underscores'), ), 
	'password' => array(
		'required' => array('rule' => array('notEmpty'), 'message' => 'A password is required'), 
		'min_length' => array('rule' => array('minLength', '6'), 'message' => 'Password must have a mimimum of 6 characters')), 
		'password_confirm' => array('required' => array('rule' => array('notEmpty'), 'message' => 'Please confirm your password'), 
		'equaltofield' => array('rule' => array('equaltofield', 'password'), 'message' => 'Both passwords must match.')), 
	'email' => array(
		'required' => array('rule' => array('email', true), 'message' => 'Please provide a valid email address.'), 
		'unique' => array('rule' => array('isUniqueEmail'), 'message' => 'This email is already in use', ), 
		'between' => array('rule' => array('between', 6, 60), 'message' => 'Usernames must be between 6 to 60 characters')), 
	'role' => array('valid' => array('rule' => array('inList', array('admin', 'user')), 'message' => 'Please enter a valid role', 'allowEmpty' => false)), 
	'password_update' => array(
		'min_length' => array('rule' => array('minLength', '6'), 'message' => 'Password must have a mimimum of 6 characters', 'allowEmpty' => true, 
		'required' => false)), 'password_confirm_update' => array('equaltofield' => array('rule' => array('equaltofield', 'password_update'), 'message' => 'Both passwords must match.', 
		'required' => false, )));
	*/
	
	function parentNode() {
	    if (!$this->id && empty($this->data)) {
	        return null;
	    }
	    if (isset($this->data['User']['group_id'])) {
	        $groupId = $this->data['User']['group_id'];
	    } else {
	        $groupId = $this->field('group_id');
	    }
	    if (!$groupId) {
	        return null;
	    } else {
	        return array('Group' => array('id' => $groupId));
	    }
	}
	

	/**
	 * Before isUniqueUsername
	 * @param array $options
	 * @return boolean
	 */
	function isUniqueUsername($check) {

		$username = $this -> find('first', array('fields' => array('User.id', 'User.username'), 'conditions' => array('User.username' => $check['username'])));

		if (!empty($username)) {
			return false;
		}
		return true;
	}
	
	function checkUserNameUpdate($name, $id){
		$data = $this->query("SELECT * from users WHERE users.username = '".$name."' and users.id<>" .$id);
		return count($data);
	}
	
	function checkUserEmailUpdate($email, $id){
		$data = $this->query("SELECT * from users WHERE users.email = '".$email."' and users.id<>" .$id);
		return count($data);
	}

	/**
	 * Before isUniqueEmail
	 * @param array $options
	 * @return boolean
	 */
	function isUniqueEmail($check) {
		$email = $this -> find('first', array('fields' => array('User.id'), 'conditions' => array('User.email' => $check['email'])));
		if (!empty($email)) {
			return false;
		} 
		return true;
	}

	public function alphaNumericDashUnderscore($check) {
		// $data array is passed using the form field name as the key
		// have to extract the value to make the function generic
		$value = array_values($check);
		$value = $value[0];

		return preg_match('/^[a-zA-Z0-9_ \-]*$/', $value);
	}

	public function equalToField($check, $otherfield) {
		//get name of field
		$fname = '';
		foreach ($check as $key => $value) {
			$fname = $key;
			break;
		}
		return $this -> data[$this -> name][$otherfield] === $this -> data[$this -> name][$fname];
	}

	/**
	 * Before Save
	 * @param array $options
	 * @return boolean
	 */
	public function beforeSave($options = array()) {
		// hash our password
		if (isset($this -> data[$this -> alias]['password'])) {
			$this -> data[$this -> alias]['password'] = AuthComponent::password($this -> data[$this -> alias]['password']);
		}

		// if we get a new password, hash it
		if (isset($this -> data[$this -> alias]['password_update']) && !empty($this -> data[$this -> alias]['password_update'])) {
			$this -> data[$this -> alias]['password'] = AuthComponent::password($this -> data[$this -> alias]['password_update']);
		}

		// fallback to our parent
		return parent::beforeSave($options);
	}

	/* callback before validate
		@author : Thanh Tran
		*/
	public function beforeValidate($options = array()){
		if (isset($this->data['User']['email'])) {
			$user_info = AuthComponent::user();
			$user = $this->findById($user_info['id']);
			if(!empty($user_info) && $this->data['User']['email'] == $user['User']['email']){
				unset($this->data['User']['email']);
			}
		}
		return true;
	}
	public function getGroupId($email){
		$sql = array(
						'fields'=> array( "User.group_id"),
                        'conditions' => array(
                        						'User.email' => $email,
                        						'User.deleted' => 0
                        					)
					);
		$data = $this->find("first", $sql);
		if(!empty($data)){
			return $data['User']['group_id'];
		}
		return -1;
	}

	/* function find user by email
	@author : Thanh Tran
	*/
	public function findByEmail($email){
		return $this->find('first',array(
			'conditions'=>array(
				'group_id'=>3,
				'email'=>$email
				)
			));
	}
	public function findById($id){
		return $this->find('first',array(
			'conditions'=>array(
				'User.id'=>$id
				)
			));
	}
	/* function find user by code
	@author : Thanh Tran
	*/
	public function findByCode($code){
		return $this->find('first',array(
			'conditions'=>array(
				'group_id'=>3,
				'code'=>$code
				)
			));
	}

	/**
	 * Validation rules
	 *
	 * @var array
	 */
	public $validate = array(
		'group_id' => array(
			'numeric' => array(
				'rule' => array('numeric'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
		'username' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'Tên đăng nhập không được để trống',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			)	
		),
		'old_password'=> array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'Mật khẩu cũ không được để trống',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'match_old_password'=> array(
				'rule' => array('match_old_password','old_password','id'),
				'message'=>'Mật khẩu cũ không đúng'
			),
		),
		'password' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'Mật khẩu không được để trống',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'minlength' => array(
				'rule'=> array('minlength',6),
				'message'=>'Mật khẩu phải có độ dài tối thiểu là 6 ký tự'
				),
		),
		'confirm_password'=> array(
			'notempty' => array(
				'rule' => array('notempty'),
				'message' => 'Xác nhận mật khẩu không được để trống',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'match_password' => array(
				'rule' => array('match_password','password'),
				'message'=>'Xác nhận mật khẩu không đúng'
			),
		),
		'email' => array(
			'email' => array(
				'rule' => array('email'),
				'message' => 'Email không được để trống',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
			'unique' => array(
				'rule'=> 'isUnique',
				'message'=>'Email đã được đăng ký, vui lòng đổi email khác'
				),
		)
	);
	public function match_password($check, $password_field = 'password'){
		$password = $this->data['User'][$password_field];
		$confirm_password = $this->data['User']['confirm_password'];
		if (strcmp($password, $confirm_password)==0) {
			return true;
		}else{
			return false;
		}
	}
	public function match_old_password($check, $password_field = 'old_password',$id_field = 'id'){
		$old_password = AuthComponent::password($this->data['User'][$password_field]);
		$id = $this->data['User'][$id_field];
		$user = $this->findById($id);
		$password = $user['User']['password'];
		if (strcmp($password,$old_password)==0) {
			return true;
		}else{
			return false;
		}
	}

}
